Ext.namespace("Plan.Add");
var userMap = null;
Plan.Add.win = function(){
	this.userSelector;
	this.selectUserId;
	this.planId;
	this.users=[];
	this.txtPlanTitle = new Ext.form.TextField({
		fieldLabel:'计划名称',
		allowBlank :false,
		width:'250',
		maxLength:50
	});
	//审核人的url
	this.auditorStore  = new Ext.data.JsonStore({
			data:[],
			fields: ['USER_ID','USER_NAME']
	});
	this.auditor = new Ext.form.ComboBox({
		width:90,
		mode:'local',
		allowBlank :false,
		triggerAction:'all',
		emptyText:'请选择...',
		fieldLabel:'审核人',
		valueField:'USER_ID',
		displayField:'USER_NAME',
		store:this.auditorStore
	});
	//计划类型的url
	this.planTypeStore  = new Ext.data.JsonStore({
			data:[],
			fields: ['PLAN_TYPE_ID','PLAN_TYPE_NAME']
	});
	this.planType = new Ext.form.ComboBox({
		width:90,
		mode:'local',
		allowBlank :false,
		triggerAction:'all',
		emptyText:'请选择...',
		fieldLabel:'计划类型',
		valueField:'PLAN_TYPE_ID',
		displayField:'PLAN_TYPE_NAME',
		store:this.planTypeStore
	});
    this.startDate = new Ext.form.DateField({
    	fieldLabel:'计划时间',
		width: 90,
		allowBlank :false,
		format: 'Y-m-d'
	});
    this.endDate = new Ext.form.DateField({
    	fieldLabel:'到',
    	labelSeparator:'',
		width: 90,
		allowBlank :false,
		format: 'Y-m-d'
	});
	this.level = new Ext.form.ComboBox({
		width: 90,
		fieldLabel: '计划等级',
        store: new Ext.data.ArrayStore({
        	fields: ['value', 'name'],
        	data: [[0, '普通'], [1, '重要']]
        }),
        value: 0,
        valueField: 'value',
        displayField: 'name',
        editable: false,
        allowBlank: false,
        mode: 'local',
        triggerAction: 'all',
        selectOnFocus: true
	});
    this.planStartDate = new Ext.form.DateField({
    	fieldLabel:'计划时间',
    	 minValue: '2007-12-14',
        disabledDays: [0, 6],
        disabledDaysText: '只能选择工作日',
		width: 90,
		format: 'Y-m-d'
	});
    this.planEndDate = new Ext.form.DateField({
    	fieldLabel:'到',
    	labelSeparator:'',
        disabledDays: [0, 6],
        disabledDaysText: '只能选择工作日',
		width: 90,
		format: 'Y-m-d'
	});
	this.planContent = new Ext.form.TextArea({
		maxLength:250,
		listeners:{
		}
	})
	this.baseInfoFs = new Ext.form.FieldSet({
		title:'计划基本信息',
		layout:'table',
		layoutConfig:{columns:3},
		items:[
			{colspan:2,layout:'form',items:[this.txtPlanTitle]},
        	{colspan:1,layout:'form',items:[this.auditor]},
        	{colspan:1,layout:'form',items:[this.planType]},
        	{colspan:1,layout:'form',items:[this.startDate]},
        	{colspan:1,layout:'form',items:[this.endDate]},
        	{colspan:1,layout:'form',items:[this.level]}
		]
	});
	
	this.store = new Ext.data.JsonStore({
		data:[],
	    autoLoad:true,
	    fields:[
	        {name:'PLAN_ITEM_ID'},
	        {name:'CREATE_DATE'},
	   		{name:'PLAN_ITEM_END_DATE'},
 			{name:'PLAN_ITEM_REMARK'},
 			{name:'PLAN_ITEM_SUBCONTENT'},
 			{name:'PLAN_ITEM_CONTENT'},
	  		{name:'ASSIGN_USER_NAME'},
	    	{name:'PLAN_ITEM_START_DATE'},
	    	{name:'PRINCIPAL_ID'},
	    	{name:'USER_JSON_STR'}
	    	
	    	
	     ]          
	 });
	  this.expander = new Ext.grid.RowExpander({
        tpl : new Ext.Template(
          '<div style="padding-left: 20px;" >',
            '<p>',
            '计划内容：<br/>{PLAN_ITEM_CONTENT}',
            '</p>',
            '</div>'
        )
    });    
	this.sm = new Ext.grid.CheckboxSelectionModel();
	this.rendererDate= function(value) {
		if (typeof value === 'string') return value;
		if(value && value!='')
            return value.format("Y-m-d");
   }
   this.renderAssigner = function(value, cellmeta, record, rowIndex, columnIndex, store){
   		if(userMap==null||Utils.getUser(record.data.PRINCIPAL_ID,userMap)==""){
   			return record.data.ASSIGN_USER_NAME;
   		}else{
   			record.data.ASSIGN_USER_NAME =Utils.getUser(record.data.PRINCIPAL_ID,userMap);
   			return Utils.getUser(record.data.PRINCIPAL_ID,userMap);
   		}
   }
	this.cm = new Ext.grid.ColumnModel([
	     this.expander,
	     this.sm,
	     {header:'id',sortable:'true',dataIndex:'PLAN_ITEM_ID',hidden:true,width:100,editor:this.planStartDate},
	     {header:'开始时间',sortable:'true',dataIndex:'PLAN_ITEM_START_DATE',width:80,editor:this.planStartDate,renderer:this.rendererDate},
	     {header:'结束时间',sortable:'true',dataIndex:'PLAN_ITEM_END_DATE',width:80,editor:this.planEndDate,renderer:this.rendererDate},
	     {header:'计划内容',sortable:'true',dataIndex:'PLAN_ITEM_SUBCONTENT',width:150,editor:this.planContent},
	     {header:'计划内容详情',sortable:'true',dataIndex:'PLAN_ITEM_CONTENT',hidden:true,width:100,editor:this.planContent},
	     {header:'处理人',sortable:'true',dataIndex:'ASSIGN_USER_NAME',width:100,
	    	 renderer:this.renderAssigner},
	     {header:'处理人id',sortable:'true',dataIndex:'PRINCIPAL_ID',hidden:true,width:70},
	     {header:'备注',sortable:'true',dataIndex:'PLAN_ITEM_REMARK',width:70,editor:new Ext.form.TextArea()}
	 ]);
			
	this.gridPanel = new Ext.grid.EditorGridPanel({
		cm:this.cm,
		height:200,
		width:500,
		store:this.store,
		loadMask: true,
		autoScroll:true,
		sm: new Ext.grid.CheckboxSelectionModel(),
		plugins: this.expander,
		tbar:[
		      {text:'新增计划项',scope:this,iconCls:'page_add',handler:this.addRow},
		      {text:'删除',scope:this,iconCls:'page_delete',handler:this.deleteRow}
		],
		bbar: new Ext.PagingToolbar({
			store: this.store,
			hidden:true,
			displayInfo: true,
			displayMsg: '显示第 {0} 条到 {1} 条记录，一共 {2} 条',
			emptyMsg: "没有记录"
		}),
		listeners:{
			celldblclick :function(grid, rowIndex, columnIndex){
				if(columnIndex==7){
					var self = grid.ownerCt.ownerCt.ownerCt;
					self.users=[];
					var store = grid.store;
					for(var i=0;i<store.getCount();i++){
						if(i == rowIndex){
							var record = store.getAt(i);
							if (record.data.PRINCIPAL_ID !=undefined){
								var array = [];
								
								var ids = record.data.PRINCIPAL_ID.split(',');
								var names =record.data.ASSIGN_USER_NAME.split(';')
								for(var i =0;i<ids.length;i++){
									var o = {}
									o.id = ids[i];
									o.name = names[i];
									if(o.name && o.name!='')
										self.users.push(o)
								}
							}
						}
					}
					
				 	self.showSelector(rowIndex)
				}
				if(columnIndex==5){
					if(!Plan.Content.win.instance){
						Plan.Content.win.instance = new Plan.Content.win();
					}
					Plan.Content.win.instance.show();
					Plan.Content.win.instance.initContent(grid.store,rowIndex,columnIndex);
				} 
			}
		}
	});           	
	
	this.planItems = new Ext.form.FieldSet({
		title:'计划子计划项',
		height:300,
		items:[
			this.gridPanel
		]
	});
	this.panel = new Ext.form.FormPanel({
		height:400,
		frame:true,
		labelWidth:60,
		items:[this.baseInfoFs,this.planItems]
	});
	this.btnSave = new Ext.Button({
		text:'保存草稿箱',
		handler:function(){this.saveOrUpdate("")},
		scope:this
	});
	this.btnSend = new Ext.Button({
		text:'保存并上报',
		handler:function(){this.saveOrUpdate("send")},
		scope:this
	});
	
	// 添加计划url
	this.addConn = new Ext.data.Connection({
		url:'../plan/addOrUptPlan.form?timesnap=' + Date.parse(new Date()),
		method:'post'
	})
	
	Plan.Add.win.superclass.constructor.call(this,{
		title:'计划信息',
	    closeAction: 'hide',
	    modal:true,
	   	frame:true,
	    width:550,
		height:420,
		items:[this.panel],
		buttonAlign:'center',
		buttons:[this.btnSave,this.btnSend ,{text:'关闭',handler:function(){this.hide()},scope:this}]//,
		//listeners:{
			//render:this.initData
		//}
	});
}
Ext.extend(Plan.Add.win,Ext.Window,{
	initData:function(){
		var conn = new Ext.data.Connection({
			url:'../plan/initPlan.form',
			method:'post'
		})
		Utils.request(conn,{
			params:{},
			scope:this,
			success:function(data){
				this.scope.auditorStore.loadData(data.checker);
				this.scope.planTypeStore.loadData(data.planType);
			}
		})
	},
	initAdd:function(){
		this.btnSave.show();
		this.btnSend.show();
		this.panel.getForm().reset();
		this.store.loadData([]);
	},
	initUpdate:function(data,detail){
		if(detail && detail=="detail"){
			this.btnSave.hide();
			this.btnSend.hide();
		}else{
			this.btnSave.show();
			this.btnSend.show();
		}
		this.panel.getForm().reset();
		this.planId=data.PLAN_ID;
		this.txtPlanTitle.setValue(data.PLAN_TITLE);
		this.auditor.setValue(data.AUDIT_ID);
		this.planType.setValue(data.PLAN_TYPE_ID);
		this.startDate.setValue(data.PLAN_START_DATE);
		this.endDate.setValue(data.PLAN_END_DATE);
  		this.level.setValue(data.PLAN_LEVEL);
  		this.store.loadData([]);
  		var conn = new Ext.data.Connection({
  			url:'../plan/searchPlanItem.form',
  			method:'post'
  		})
  		Utils.request(conn,{
  			params:{
  				planId:this.planId
  			},
  			scope:this,
  			success:function(data){
  				var result = data.result;
  				userMap = Utils.getUserName(data.userNames);
  				for(var i=0;i<result.length;i++){
  					result[i].PLAN_ITEM_START_DATE = Date.parseDate(result[i].PLAN_ITEM_START_DATE,'Y-m-d');
  					result[i].PLAN_ITEM_END_DATE = Date.parseDate(result[i].PLAN_ITEM_END_DATE,'Y-m-d');
  					result[i].PLAN_ITEM_SUBCONTENT = Utils.getSubHTMLData(result[i].PLAN_ITEM_CONTENT,40);
  				}
  				this.scope.store.loadData(data.result);
  			}
  		})
	},
	saveOrUpdate:function(isSend){
		if(!this.panel.getForm().isValid()){
			return;
		}
		var cnt = this.store.getCount();
		if (cnt === 0) {
			Utils.info('您还没添加子计划!');
			return;
		};
		for(var i = 0; i < cnt; i++){
			var record = this.store.getAt(i);
			if(record.data.PLAN_ITEM_START_DATE == ''){
				Utils.info("第"+(i+1)+"行，开始时间没有填写");
				return;
			}
			if(record.data.PLAN_ITEM_END_DATE == ''){
				Utils.info("第"+(i+1)+"行，结束时间没有填写");
				return;
			}
			if(record.data.PLAN_ITEM_SUBCONTENT == ''){
				Utils.info("第"+(i+1)+"行，计划内容没有填写");
				return;
			}
			if(record.data.PRINCIPAL_ID == ''){
				Utils.info("第"+(i+1)+"行，处理人没有填写");
				return;
			}
			if(record.data.PLAN_ITEM_REMARK.length>50){
				Utils.info("第"+(i+1)+"行,备注长度应该小于50");
				return;
			}
		}
		var planItems =[];
		var store = this.store;
		var planparam = [] ;
		//id|开始时间|结束时间|内容|负责人|备注
		for(var i=0 ;i<store.getCount();i++){
			var data = store.getAt(i).data;
			var temp  =[];
			temp.push(data.PLAN_ITEM_ID==""?' ':data.PLAN_ITEM_ID);
			temp.push(data.PLAN_ITEM_START_DATE.format("Y-m-d"));
			temp.push(data.PLAN_ITEM_END_DATE.format("Y-m-d"));
			temp.push(data.PLAN_ITEM_CONTENT);
			temp.push(data.PRINCIPAL_ID);
			temp.push(data.PLAN_ITEM_REMARK==""?' ':data.PLAN_ITEM_REMARK);
			planparam.push(temp.join(Utils.SUB_SEPARATOR));
		}
		var plan_status ='4';
		if(isSend&&isSend=="send")
		  plan_status ='0';
		Utils.request(this.addConn,{
			params:{
				planId:this.planId,
				planTitle:this.txtPlanTitle.getValue(),
				auditor:this.auditor.getValue(),
				planType:this.planType.getValue(),
				startDate:this.startDate.getRawValue(),
				endDate:this.endDate.getRawValue(),
			    planItems:planparam.join(Utils.SEPARATOR),
			    level:this.level.getValue(),
			    orage:0,
			    plan_status:plan_status
			},
			scope:this,
			success:function(){
				Utils.info("操作成功！");
				this.scope.hide();
				Plan.Prepare.panel.instance.store.reload();
			}
		})
	},
	addRow :function(){
		var record = new Ext.data.Record({
	        PLAN_ITEM_ID:'',
	        PLAN_ITEM_START_DATE:'',
	        PLAN_ITEM_END_DATE:'',
	        PLAN_ITEM_SUBCONTENT:'',
	        PLAN_ITEM_REMARK:'',
	        ASSIGN_USER_NAME:'',
	        PRINCIPAL_ID:'',
	        CREATE_DATE:new Date()
	    });
	    this.gridPanel.stopEditing();
	    this.gridPanel.store.insert(0, record);
	    this.gridPanel.view.refresh();
	    this.gridPanel.startEditing(0,2);
	},
	deleteRow:function(){
		var sm =this.gridPanel.getSelectionModel();
		var record = sm.getSelections();  
		if(record.length==0){
			Utils.warn('请选择计划子项！');
			return;
		}
		Ext.Msg.confirm("信息","确认删除?",function(btn){
			if(btn=="yes"){
				var delId = [];
				for(var i=0;i<record.length;i++){
					if(record[i].data.PLAN_ITEM_ID&&record[i].data.PLAN_ITEM_ID!='')
						delId.push(record[i].data.PLAN_ITEM_ID)
				}
				conn = new Ext.data.Connection({
					url:'../plan/delPlanItem.form'
				})
				Utils.request(conn,{
					params:{planItemId:delId},
					scope:this,
					success:function(){
						Utils.info("操作成功！")
						for(var i=0;i<record.length;i++){
							this.scope.gridPanel.store.remove(record[i]);
						}
						this.scope.gridPanel.view.refresh();
					}
				})
				
			}
		},this);
	},
	showContent:function(){
		if(!Plan.Content.win.instance){
			Plan.Content.win.instance = new Plan.Content.win();
		}
		Plan.Content.win.instance.show();
	},
	showSelector: function(rowIndex) {
		if (!this.userSelector) {
			this.userSelector = new Selector.User(this, '执行人',false,rowIndex);
		}
		//this.userSelector.show([{id: '22', name: '史徐华'},{id:33, name:'shadow'}]);
		this.userSelector.initUsers(this.users);
		this.userSelector.show();
	},
	setUsers: function(o,rowIndex) {	// for Selector.User callback
		this.users = o;
		var names = [];
		this.selectUserId =[];
		for(var i=0, u; u = this.users[i++];) {
			names.push(u.name);
			this.selectUserId.push(u.id);
		}
		var store = this.store;
		var data =[];
		for(var j=0;j<store.getCount();j++){
			var rowData = store.getAt(j).data;
			if(j==rowIndex){
				rowData.ASSIGN_USER_NAME=names.join(';');
				rowData.PRINCIPAL_ID=this.selectUserId.join(',');
			}
			data.push(rowData);
		}
		store.loadData(data);
	}
})